package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.domain.ucenter.response.UcenterCode;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class AuthFilter extends ZuulFilter {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    RequestContext requestContext = null;
    HttpServletRequest request = null;
    HttpServletResponse response = null;

    @Override
    public Object run() throws ZuulException {
        //        获取request对象
        requestContext = RequestContext.getCurrentContext();
        request = requestContext.getRequest();
        response = requestContext.getResponse();


//        获取请求头是否带有Authorization
        String header = request.getHeader("Authorization");
        if (StringUtils.isEmpty(header) || !header.startsWith("Bearer ")) {
            failResult();
            return null;
        }

//        检查是否携带cookie,并且是否携带令牌
        String cookie = getCookie();
        if (StringUtils.isEmpty(cookie)) {
            return null;
        }
//        检查redis中令牌是否过期
        String key = "user_token:" + cookie;
        boolean expire = findExpire(key);
        if (expire) {
//            认证通过
            return null;
        }
        failResult();
        return null;
    }

    /**
     * @Description: 登录失败响应
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private void failResult() {

        response.setContentType("application/json;charset=utf-8");
//            设置响应信息
        ResponseResult responseResult = new ResponseResult(UcenterCode.UCENTER_LOGIN_ERROR);
        String jsonString = JSON.toJSONString(responseResult);
        requestContext.setResponseBody(jsonString);
        response.setStatus(200);
    }

    /**
     * @Description: 读取cookie
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private String getCookie() {
        Map<String, String> map = CookieUtil.readCookie(request, "uid");
        String uid = map.get("uid");
        if (StringUtils.isEmpty(uid)) {
            return null;
        }
        return uid;
    }

    /**
     * @Description: reidis中查询令牌是否过期
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private boolean findExpire(String key) {
        Long expire = stringRedisTemplate.getExpire(key);
        return expire > 0;
    }
}
